package com.gordon.moiveplayer;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Explorer extends AppCompatActivity {

    public View view = null;
    public ExpandableListView expandlist = null;
    public LayoutInflater inflater = null;
    public ArrayList<GroupBean> groupList = null;
    public LinearLayout partition_content = null;
    public TextView partition_title = null;
    public ListView file_list = null;
    public ArrayList<FileBean> fileList = null;
    public ImageView icon = null;
    public int currItemPosition = 0;
    public String getCurrItemPath = null;
    FileAdapter fileAdapter = null;
    MyAdpter diskAdpter = null;
   // ArrayAdapter<String> testadapter;
    final static String TAG = "Explorer";
    public String oldDir = "";
    int currGroupId = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_explorer);

        expandlist = (ExpandableListView) findViewById(R.id.expand_list);
        partition_content = (LinearLayout) findViewById(R.id.partition_content);
        partition_title = (TextView) findViewById(R.id.partition_title);
        file_list = (ListView) findViewById(R.id.file_list);
        partition_content.setVisibility(View.GONE);
        inflater = LayoutInflater.from(Explorer.this);
        icon = (ImageView) findViewById(R.id.file_icon);
        int i = 0,j = 0;
        groupList = new ArrayList<GroupBean>();
        fileList = new ArrayList<FileBean>();
        //fileList = new ArrayList<String>();
        fileAdapter = new FileAdapter(this,R.layout.file_item,fileList);
       // String[] strs = {"1","2","3","4","5"};
        //testadapter = new ArrayAdapter<String>(this,,strs);

        ArrayList<String> filePath = getDevList();
        for (i = 0;i < filePath.size();i++)
        {
            //group
            GroupBean groupBean = new GroupBean();
            groupBean.index = i+1;
            groupBean.name = filePath.get(i);
            groupBean.path = filePath.get(i);
            groupBean.list = new ArrayList<ChildBean>();
            groupList.add(groupBean);
        }
        diskAdpter = new MyAdpter();
        expandlist.setAdapter(diskAdpter);
        expandlist.requestFocus();
        expandlist.setSelection(0);
        expandlist.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                //expandlist.
//                if (expandlist.isGroupExpanded(groupPosition))
//                    expandlist.collapseGroup(groupPosition);
//                else                   expandlist.expandGroup(groupPosition);
                expandlist.setVisibility(View.GONE);
                partition_content.setVisibility(View.VISIBLE);
                partition_title.setText(groupList.get(groupPosition).name);
               // File current = new File(groupList.get(groupPosition).path);
                initFileList(groupList.get(groupPosition).path);
                currGroupId = groupPosition;
                file_list.setAdapter(fileAdapter);
                //file_list.setAdapter(testadapter);

                Log.d(TAG,"get file finish");
                return true;
            }
        });
        expandlist.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                //Toast.makeText(Explorer.this,"Group Collapse click",Toast.LENGTH_SHORT).show();
                //expandlist.collapseGroup(groupPosition);

            }
        });
        expandlist.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {

               // Toast.makeText(Explorer.this,"Group Expand click",Toast.LENGTH_SHORT).show();
             //   expandlist.expandGroup(groupPosition);

                //groupList.get(groupPosition).path;Environment.getExternalStoragePublicDirectory(groupList.get(groupPosition).path);
                //getExternalStorageDirectory(groupList.get(groupPosition).path);
            }
        });


        expandlist.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                return true;
            }
        });


        file_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String path= groupList.get(currGroupId).path+"/"+fileList.get(position).name;
                Log.d(TAG,"Open SUB file:path"+path);
                currItemPosition = position;
                getCurrItemPath = path;
                if (!initFileList(path)){
                    if (isMoive(path)){
                        Intent intent = new Intent();
                        intent.setClassName("com.gordon.moiveplayer","com.gordon.moiveplayer.PlayActivity");
                        intent.putExtra("name",getCurrItemPath);
                        intent.putExtra("network",false);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                }
            }
        });

        initView();
    }

    boolean isMoive(String name){
        int pathLen =  name.lastIndexOf('.');
        String type;
        Log.d(TAG,"pathLen="+pathLen);
        if (pathLen == -1)
            return false;
        type = name.substring(pathLen+1);
        Log.d(TAG,"type="+type);
        if (type.equalsIgnoreCase("mp4")||type.equalsIgnoreCase("mkv")
                ||type.equalsIgnoreCase("ts")||type.equalsIgnoreCase("mp4"))
            return true;
        else
            return false;
    }

    boolean initFileList(String path){
        File current = new File(path);
        if (current.isDirectory()) {
            fileList.clear();

            if (currGroupId >= groupList.size())
                currGroupId = 0;

            groupList.get(currGroupId).path = path;
            for (File mFile : current.listFiles()) {
                FileBean fileBean = new FileBean();
                if (mFile.isFile()) {
                    if (isMoive(mFile.getName()))
                        fileBean.fileType = 2;
                    else
                        fileBean.fileType = 0;
                } else if (mFile.isDirectory()){
                    fileBean.fileType = 1;
                }
                fileBean.name = mFile.getName();
                Log.d(TAG, "get sub file:" + fileBean.name);
                //fileList.add(fileBean.name);
                fileList.add(fileBean);
            }
            fileAdapter.notifyDataSetChanged();
        }else
            return false;

        return true;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        //
        Log.d(TAG,"get CURRENT win getSelectedPosition= "+expandlist.getSelectedPosition());
            if (expandlist.getVisibility() == View.GONE) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        if (groupList.get(currGroupId).name.equals(groupList.get(currGroupId).path)){
                            expandlist.setVisibility(View.VISIBLE);
                            partition_content.setVisibility(View.GONE);
                            fileList.clear();
                            ArrayList<String> filePath = getDevList();
                            groupList.clear();
                            for (int i = 0;i < filePath.size();i++)
                            {
                                //group
                                GroupBean groupBean = new GroupBean();
                                groupBean.index = i+1;
                                groupBean.name = filePath.get(i);
                                groupBean.path = filePath.get(i);
                                groupBean.list = new ArrayList<ChildBean>();
                                groupList.add(groupBean);
                            }
                            diskAdpter.notifyDataSetChanged();
                            return true;
                        }else {
                            int pathLen =  groupList.get(currGroupId).path.lastIndexOf('/');
                            Log.d(TAG, "path:"+groupList.get(currGroupId).path+",pathLen = " + pathLen);
                            if (pathLen != -1) {
                                String path = groupList.get(currGroupId).path.substring(0,pathLen);
                                String dir = groupList.get(currGroupId).path.substring(pathLen+1);
                                oldDir = dir;
                                Log.d(TAG, "pathLen = " + pathLen + "PATH :" + path);
                                initFileList(path);
                            }
                            return true;
                        }

                    case KeyEvent.KEYCODE_DPAD_CENTER:
                    {
                       // fileList.
                       // int pathLen =  groupList.get(currGroupId).path.lastIndexOf('/');
                        break;
                    }
                }
            }
        return super.onKeyUp(keyCode, event);
    }

    class FileAdapter extends ArrayAdapter<FileBean>{
        int resourceId;

        public FileAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<FileBean> objects) {
            super(context, resource, objects);
            resourceId= resource;
        }

        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            //return super.getView(position, convertView, parent);
            View view = null;
            LinearLayout imageListView;
            //if (convertView != null)
            if (false)
            {
                view = convertView;
                TextView txt = (TextView) view.findViewById(R.id.file_item);
                //TextView txt = (TextView)view.getTag();
                ImageView img = (ImageView) view.findViewById(R.id.file_icon);
                txt.setText(fileList.get(position).name);
                if (fileList.get(position).fileType == 0)
                    img.setImageResource(R.drawable.form);
                else if (fileList.get(position).fileType == 1)
                    img.setImageResource(R.drawable.folder);
                else if (fileList.get(position).fileType == 2)
                    img.setImageResource(R.drawable.video);

            }else {
                //LayoutInflater inflater = getLayoutInflater();
                imageListView = new LinearLayout(getContext());
                LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(resourceId,imageListView,true);
                //view = LayoutInflater.from(Explorer.this);
                //view = View.inflate(Explorer.this,resourceId,null);
                TextView txt = (TextView) view.findViewById(R.id.file_item);
                if (fileList.get(position).name.equals(oldDir))
                    file_list.setSelection(position);
                txt.setText(fileList.get(position).name);
                ImageView img = (ImageView) view.findViewById(R.id.file_icon);
                view.setTag(txt);
                if (fileList.get(position).fileType == 0)
                    img.setImageResource(R.drawable.form);
                else if (fileList.get(position).fileType == 1)
                    img.setImageResource(R.drawable.folder);
                else if (fileList.get(position).fileType == 2)
                    img.setImageResource(R.drawable.video);
            }
            return imageListView;
        }

    }

    public ArrayList<String> getDevList(){
        ArrayList<String> devList = new ArrayList<String>();
        File file = Environment.getExternalStorageDirectory();
        if (file != null)
            devList.add(file.getPath());

        File usbFile = new File("/mnt/sda/");
        if (usbFile.exists()){
            for (File mFile : usbFile.listFiles())
            {
                if (mFile.exists() && mFile.isDirectory()){
                    devList.add(mFile.getPath());
                    Log.d(TAG,"add file:"+mFile.getPath());
                    Log.d(TAG,"add file name:"+mFile.getName());
                }
            }
        }

        return devList;
    }


    class MyAdpter extends BaseExpandableListAdapter{
        @Override
        public int getGroupCount() {
            return groupList.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return groupList.get(groupPosition).list.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groupList.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return groupList.get(groupPosition).list.get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupList.get(groupPosition).index;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            View view = null;
            if (convertView != null)
            {
                view = convertView;
                TextView txt = (TextView)view.getTag();
                txt.setText(groupList.get(groupPosition).name);
            }else{
                view = View.inflate(Explorer.this,R.layout.group,null);
                TextView txt = (TextView)view.findViewById(R.id.group_text);
                txt.setText(groupList.get(groupPosition).name);
                view.setTag(txt);
            }
            return view;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            View view = null;
            if (convertView != null)
            {
                view = convertView;
                ChildHolder holder = (ChildHolder)view.getTag();
                holder.text1.setText(groupList.get(groupPosition).list.get(childPosition).name);
                holder.text2.setText(groupList.get(groupPosition).list.get(childPosition).descriptor);
            }else{
                view = View.inflate(Explorer.this,R.layout.child,null);
                ChildHolder holder = new ChildHolder();
                holder.text1  = (TextView)view.findViewById(R.id.child_layer1_txt);
                holder.text2  = (TextView)view.findViewById(R.id.child_layer2_txt);
                holder.text1.setText(groupList.get(groupPosition).list.get(childPosition).name);
                holder.text2.setText(groupList.get(groupPosition).list.get(childPosition).descriptor);
                view.setTag(holder);
            }
            return view;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }
    }

    class ChildHolder{
        TextView text1;
        TextView text2;
    }
    class FileBean{
        String name;
        int fileType; //0: file   1: dir   2:moive
    }
    public void initView(){
        //view = LayoutInflater.from(Explorer.this);

       // int count = groupList.size();
       // for (int i= 0; i < count;i++)
         //   expandlist.expandGroup(i);
    }
}
